package com.heima.comment.service.impl;

import com.heima.aliyun.GreeTextScan;
import com.heima.comment.dtos.CommentRepayDto;
import com.heima.comment.dtos.CommentRepayLikeDto;
import com.heima.comment.dtos.CommentRepaySaveDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.comment.vo.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j2
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;

    @Autowired
    GreeTextScan greeTextScan;

    /**
     * 查看更多回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //每页显示10条数据
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        //按照时间倒叙进行查询,分页
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(
                Criteria.where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate())
                ).limit(dto.getSize()).
                        with(Sort.by(Sort.Direction.DESC, "createdTime"))
                , ApCommentRepay.class);

        //沒登陸的话显示所有的評論數據並返回就可以了
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        ApUser userById = userFeign.findUserById(user.getId());
        if (userById == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        List<String> collect = apCommentRepays.stream().map(x -> x.getId()).collect(Collectors.toList());
        //遍历当前文章的所有评论信息,去取出当前文章内所有评论的id
        //查询当前用户在当前页面中的所有已经点赞的评论
        List<ApCommentRepayLike> myLikeApRepayComments = mongoTemplate.find(Query.query(
                Criteria.where("commentRepayId").in(collect)
                        .and("authorId").is(userById.getId())
                        .and("operation").is((short) 0))
                , ApCommentRepayLike.class);

        if (apCommentRepays != null && apCommentRepays.size() > 0
                && myLikeApRepayComments != null && myLikeApRepayComments.size() >= 0
        ) {
            List resultList=new ArrayList();
            apCommentRepays.stream().forEach(
                    x -> {
                        ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                        BeanUtils.copyProperties(x, apCommentRepayVo);
                        //查询所有当前我已点赞的评论的主键id
                        myLikeApRepayComments.forEach(
                                myLikeApRepayComment->{
                                    if (x.getId().equals(myLikeApRepayComment.getCommentRepayId())){
                                        apCommentRepayVo.setOperation((short)0);
                                    }
                                }
                        );
                        resultList.add(apCommentRepayVo);
                    }
            );
            return ResponseResult.okResult(resultList);
        }
        return ResponseResult.okResult(apCommentRepays);
    }

    /**
     * 保存回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null
                || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"非法参数异常");
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "文本内容过长,请缩减后提交");
        }
        ApUser userById = AppThreadLocalUtils.getUser();
        if (userById == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        ApUser user = userFeign.findUserById(userById.getId());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前登录状态异常,请重新登录");
        }
        //阿里云远程调用判断当前是否可以发布相关信息
        try {
            Map map = greeTextScan.greeTextScan(dto.getContent());
            if (map.get("suggestion").equals("block")) {
                //文章中包含敏感信息直接拒绝
                return ResponseResult.errorResult(AppHttpCodeEnum.ILLEGAL_OPERATION, "回复内容中包含敏感信息不可发布");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCommentId(dto.getCommentId());
        mongoTemplate.insert(apCommentRepay);
        //****更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //参数校验
        if (dto == null || dto.getCommentRepayId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询评论回复   根据评论回复的id进行查询
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "相关评论信息已经不存在,无法进行点赞操作");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //未登錄無法點贊
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "登錄后才可以进行点赞操作");
        }
        ApUser userById = userFeign.findUserById(user.getId());
        if (userById == null) {
            //如果當前登錄的賬號查詢不到也不可以进行点赞操作
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到当前登录的账号信息");
        }

        //评论存在且当前账号没有对此评论点赞则可以点赞    //查询当前回复点赞信息是否存在
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(
                Criteria.where("authorId").is(userById.getId())
                        .and("commentRepayId").is(dto.getCommentRepayId()))
                , ApCommentRepayLike.class);
        //当前的点赞操作存在且是点赞状态,非法操作,全部判断完毕
        if ((apCommentRepayLike != null && apCommentRepayLike.getOperation() == 0 && dto.getOperation() == 0)
                || (apCommentRepayLike != null && apCommentRepayLike.getOperation() == 1 && dto.getOperation() == 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ILLEGAL_OPERATION, "无法进行重复点赞(或者取消点赞)操作");
        }
        if (apCommentRepayLike == null) {
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(userById.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
        }
        apCommentRepayLike.setOperation(dto.getOperation());
        mongoTemplate.save(apCommentRepayLike);//保存当前的点赞行为信息

        //这里都是合法状态
        if (dto.getOperation() == 1) {
            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1 < 0 ? 0 : apCommentRepay.getLikes() - 1);
        } else apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);

        mongoTemplate.save(apCommentRepay);

        //返回的是点赞数
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}